package com.hdmp.auth.shiro;

import com.google.common.base.Strings;
import com.hdmp.tool.bean.ResultBean;
import com.hdmp.tool.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: Chenyc
 * @Date: 2019/5/26 15:28
 */
@Slf4j
public class SysUserFilter extends PathMatchingFilter {

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception{
        System.out.println("11111111111111111111111111111111111");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (!Strings.isNullOrEmpty(username) && !Strings.isNullOrEmpty(password)) {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                subject.login(token);
                return true;
            } catch (AuthenticationException e) {
                e.printStackTrace();
                System.out.println(username + ",longin failure exception:" + "\n" + e.getMessage());
                log.error("账户或密码不正确");
                ResultBean resultBean = new ResultBean();
                resultBean.setCode(500);
                resultBean.setMsg("系统提示：账户或密码错误！");
                printResponse(request, resultBean, response);
                return false;
            }
        }
        return true;
    }

    private void printResponse(ServletRequest request, ResultBean<String> resultBean, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", ((HttpServletRequest)request).getHeader("Origin"));
        String message = JsonUtils.toJson(resultBean);
        try {
            PrintWriter out = httpResponse.getWriter();
            out.println(message);
            System.out.println();
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}